package com.meepo.basic.schema.feed

import com.meepo.basic.Consts
import com.meepo.basic.schema.Enums
import com.meepo.basic.schema.user.User
import java.io.Serializable

data class Item(
    val id: String = "",
    val title: String? = "",
    val desc: String? = "",
    private val covers: List<Resource>? = arrayListOf(),
    val source: Source?,
    val categories: List<Category>?,
    private val style: Style?,
    val content: Resource?,
    val supplements: List<Supplement>?,
    val h5: Resource?,
    val author: User?,
    var stat: Stat?,
    val attitudes: List<Attitude>? = arrayListOf(),
    val topic: Topic?,
    val tags: List<Tag>?
) : Serializable {

    data class Supplement(
        val value: String
    ) : Serializable

    data class Style(
        val viewType: String
    ) : Serializable

    fun getViewType(): String {
        return style?.viewType ?: Enums.VIEW_TYPE_BIG_VERTICAL
    }


    fun getCovers(): List<Resource> {
        var newCovers = covers?.filter { c -> !c.content.isNullOrEmpty() } ?: return emptyList()

        if (newCovers.size > Consts.Feed.MAX_IMAGE_COUNT) {
            newCovers = newCovers.subList(0, Consts.Feed.MAX_IMAGE_COUNT)
        }

        return newCovers
    }

    fun findOneCover(): String {
        covers?.let {
            if (it.isNotEmpty()) {
                return it[0].content ?: ""
            }
        }
        return ""
    }

    fun findCategory(): String {
        categories?.let {
            if (it.isNotEmpty()) {
                return it[0].name
            }
        }

        return ""
    }

    fun isCollected(): Boolean {
        this.stat?.let {
            return it.collected
        }

        return false
    }

    fun isLiked(): Boolean {
        this.stat?.let {
            return it.liked
        }

        return false
    }

    fun notifyLikeChanged(): Item {
        if (isLiked()) {
            this.stat!!.liked = false
            this.stat!!.likedCount -= 1
        } else {

            if (this.stat != null) {
                this.stat!!.liked = true
                this.stat!!.likedCount += 1
            } else {
                this.stat = Stat(liked = true, likedCount = 1)
            }
        }

        return this
    }


    override fun equals(other: Any?): Boolean {
        return other != null && other is Item && other.id == this.id
    }

    override fun hashCode(): Int {
        return this.id.hashCode()
    }


}